<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="商户名称">
                <a-input placeholder="请输入商户名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="员工名称">
                <a-input placeholder="请输入员工名称" v-model="queryParam.salesman_name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-row style="background: white; padding: 15px">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList">
          <a-radio-button value="0"> 全部 </a-radio-button>
          <a-radio-button value="1"> 未绑定 </a-radio-button>
          <a-radio-button value="2"> 已绑定 </a-radio-button>
          <a-radio-button value="3"> 已上线 </a-radio-button>
        </a-radio-group>
        <div>
          <a-button type="primary" @click="showAdd = true">+ 新增</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="deleteCode(1)">批量删除</a-menu-item>
              <a-menu-item @click="allDownload">批量下载</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>
      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        size="default"
        :columns="columns"
        :data-source="list"
        :customRow="customRow"
        :scroll="{ x: 'max-content' }"
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange
        }"
      >
        <div slot="name" slot-scope="record">
          <div class="name" v-if="record.store_id != 0">
            <div class="pic">
              <img :src="record.store_logo" alt="" v-if="record.store_logo" />
              <img src="../../assets/images/diy/goodExample.png" alt="" v-else />
            </div>
            <div class="info">
              <span>{{ record.store_name || '-' }}</span>
              <span>{{ record.category_name || '-' }}</span>
            </div>
          </div>
          <span v-else>-</span>
        </div>
        <span slot="salesman_name" slot-scope="text"> {{ text || '-' }} </span>
        <span slot="bussiness_no" slot-scope="text"> {{ text || '-' }} </span>
        <span slot="admin_name" slot-scope="text"> {{ text || '-' }} </span>
        <span slot="shop_bind_time" slot-scope="text">
          {{ text > 0 ? $moment(text * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>
        <span slot="mini_time" slot-scope="text">
          {{ text > 0 ? $moment(text * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>
        <div slot="status" slot-scope="text" class="status">
          <span :class="text == 1 ? 'grey' : text == 2 ? 'orange' : text == 3 ? 'green' : ''"></span>
          <span v-if="text == 1">未绑定</span>
          <span v-if="text == 2">已绑定</span>
          <span v-if="text == 3">已上线</span>
        </div>

        <div slot="register" slot-scope="text, scope">
          <template v-if="scope.store_id !== '0'">
            <a-button type="link" size="small" v-if="!scope.ali_status" @click="bindQrcode(scope.id, 2)"
              >支付宝</a-button
            >
            <a-button type="link" size="small" v-if="!scope.wx_status" @click="bindQrcode(scope.id, 1)">微信</a-button>
          </template>
          <span v-else>-</span>
        </div>

        <div slot="action" slot-scope="text, scope">
          <div class="action">
            <a-button type="link" size="small" @click="creatCode([scope.id], ['二维码' + scope.id], 2)">下载</a-button>
            <a-divider type="vertical" style="margin:0 1px;" />
            <a-dropdown>
              <a-button type="link" size="small">更多<a-icon type="down"/></a-button>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a-button type="link" size="small" @click="creatCode([scope.id], ['二维码' + scope.id], 1, scope)"
                    >二维码</a-button
                  >
                </a-menu-item>
                <a-menu-item>
                  <a-button type="link" size="small" @click="deleteCode(2, [scope.id])">删除</a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-button type="link" size="small" @click="toShowBand(scope)" :disabled="scope.status != 1"
                    >绑定商城</a-button
                  >
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </div>
      </a-table>
    </a-row>
    <!-- 新增二维码弹窗 -->
    <a-modal v-model="showAdd" title="新增收款码" :afterClose="afterClose" @ok="addNumber" :confirmLoading="btnLoading">
      <a-form-model-item label="新增数量" required :labelCol="{ span: 4 }" :wrapperCol="{ span: 18 }">
        <a-input v-model="number" placeholder="请输入收款码数量"></a-input>
      </a-form-model-item>
    </a-modal>
    <!-- 展示二维码弹窗 -->
    <a-modal v-model="showCode" title="二维码" :afterClose="afterClose" @ok="showCode = false">
      <div class="code">
        <img :src="codeUrl" alt="" />
        <span>关联商城:{{ currentCode.store_name || '暂无' }}</span>
      </div>
      <div class="btns">
        <a-button type="link" @click="downloadIamge(codeUrl, '二维码' + currentCode.id)">下载二维码</a-button>
        <a-button v-if="currentCode.status != 1" style="margin-left: 10px" type="link">复制商城名称</a-button>
      </div>
    </a-modal>
    <!-- 二维码绑定商城 -->
    <a-modal v-model="showBand" title="绑定商城" :afterClose="afterClose" @ok="bandStore" :confirmLoading="btnLoading">
      <a-form-model-item label="选择商城" required :labelCol="{ span: 4 }" :wrapperCol="{ span: 18 }">
        <a-select
          v-model="choosedStore"
          style="width: 200px"
          :filter-option="filterOption"
          show-search
          @change="handleSearch"
        >
          <a-select-option :value="item.id" v-for="item in storeList" :key="item.id"> {{ item.name }} </a-select-option>
        </a-select>
      </a-form-model-item>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
const columns = [
  {
    title: 'id',
    dataIndex: 'id'
  },
  {
    title: '店铺信息',
    width: 300,
    scopedSlots: {
      customRender: 'name'
    }
  },
  {
    title: '业务员',
    dataIndex: 'salesman_name',
    scopedSlots: {
      customRender: 'salesman_name'
    }
  },
  {
    title: '代理',
    dataIndex: 'admin_name',
    scopedSlots: {
      customRender: 'admin_name'
    }
  },
  {
    title: '商户号',
    dataIndex: 'bussiness_no',
    scopedSlots: {
      customRender: 'bussiness_no'
    }
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: {
      customRender: 'status'
    }
  },
  {
    title: '绑定时间',
    dataIndex: 'shop_bind_time',
    scopedSlots: {
      customRender: 'shop_bind_time'
    },
    sorter: (a, b) => a.shop_bind_time - b.shop_bind_time
  },
  {
    title: '上线时间',
    dataIndex: 'mini_time',
    scopedSlots: {
      customRender: 'mini_time'
    },
    sorter: (a, b) => a.mini_time - b.mini_time
  },
  {
    title: '注册',
    scopedSlots: {
      customRender: 'register'
    }
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action'
    }
  }
]
import { list, add, code, deleteCode, bandStore, bindQrcodeOnline } from '@/api/saas/moneyCode'
export default {
  data() {
    return {
      totalCount: 0,
      // 表头
      columns,
      // 查询参数
      queryParam: {
        name: '',
        salesman_name: '',
        page: 1,
        status: '0'
      },
      // 数据列表
      list: [],
      // 选中行的id
      selectedRowKeys: [],
      // 新增数量
      number: '',
      // 新增收款码弹窗
      showAdd: false,
      // 按钮加载状态
      btnLoading: false,
      // 二维码地址
      codeUrl: '',
      // 展示二维码的弹窗
      showCode: false,
      // 正在展示二维码的数据
      currentCode: {},
      // 所有商城列表
      storeList: [],
      // 是否展示绑定商城的弹窗
      showBand: false,
      // 选中商城的id
      choosedStore: '',
      // 业务员列表
      salesman_list: [],
      // 选中的业务员id
      choosedSalesman: ''
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleSearch(value) {
      let [item] = this.storeList.filter((d, index) => {
        return d.id == value
      })
      this.choosedStore = item.id
    },
    // 获取数据列表
    async getList() {
      const hide = this.$message.loading('加载中', 0)
      const res = await list(this.queryParam)
      if (res.code == 0) {
        this.totalCount = res.totalCount
        this.list = res.data
        this.storeList = res.store_list
        this.salesman_list = res.salesman_list
      }
      hide()
    },
    // 分页请求
    tablePageChange(e) {
      this.queryParam.pageNo = e
      this.getList()
    },
    // 选中多行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    afterClose() {
      this.number = ''
      this.btnLoading = false
      this.currentCode.url = ''
      this.currentCode.store = ''
      this.choosedStore = ''
      this.choosedSalesman = ''
    },
    // 点击添加收款码
    async addNumber() {
      if (!this.number) {
        return this.$message.warning('请填入新增的数量')
      }
      console.log(this.number)
      this.btnLoading = true
      const res = await add({ number: this.number })
      if (res.code == 0) {
        this.getList()
        this.showAdd = false
        this.btnLoading = false
      }
    },
    // 保存二维码
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function() {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png') //得到图片的base64编码数据

        var a = document.createElement('a') // 生成一个a元素
        var event = new MouseEvent('click') // 创建一个单击事件
        a.download = name || 'photo' // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = imgsrc
    },
    // 点击批量下载二维码
    allDownload() {
      if (!this.selectedRowKeys.length) {
        return
      }
      this.creatCode(this.selectedRowKeys, this.selectedRowKeys, 2)
    },
    // 生成二维码
    async creatCode(ids, names, type, currentCode) {
      const res = await code({ ids })
      if (res.code == 0) {
        if (type == 1) {
          this.currentCode = currentCode
          this.codeUrl = res.data[0]
          this.showCode = true
        }
        if (type == 2) {
          res.data.forEach((item, index) => {
            this.downloadIamge(item, names[index])
          })
        }
      }
    },
    // 删除二维码
    deleteCode(type, ids) {
      let id = []
      const that = this
      if (type == 1) {
        if (!this.selectedRowKeys.length) {
          return
        }
        id = this.selectedRowKeys
      }
      if (type == 2) {
        id = ids
      }
      this.$confirm({
        title: '是否确认删除?',
        onOk() {
          that.delete(id)
        },
        onCancel() {}
      })
    },
    async delete(ids) {
      const res = await deleteCode({ ids })
      if (res.code == 0) {
        this.getList()
      }
    },
    toShowBand(e) {
      this.currentCode = e
      this.showBand = true
    },
    async bandStore() {
      if (!this.choosedStore) {
        this.$message.warning('请选择商城')
        return
      }
      this.btnLoading = true
      let param = {}
      if (this.showSalesman) {
        param.id = this.currentCode.id
        param.store_id = this.choosedStore
        param.salesman_id = this.choosedSalesman
      } else {
        param.id = this.currentCode.id
        param.store_id = this.choosedStore
      }
      const res = await bandStore(param)
      if (res.code == 0) {
        this.showBand = false
        this.getList()
      }
      this.btnLoading = false
    },

    async bindQrcode(id, type) {
      const hide = this.$message.loading('绑定中', 0)
      const res = await bindQrcodeOnline({
        id,
        type
      })
      if (res.code == 0) {
        this.$message.success(res.msg)
        this.getList()
      }
      hide()
    }
  },
  mounted() {
    this.getList()
  },
  computed: {
    showSalesman() {
      if (!this.choosedStore) {
        return true
      }
      let index = this.storeList.findIndex(item => {
        return item.id == this.choosedStore
      })
      if (index > -1) {
        let store = this.storeList[index]
        if (store.salesman_id > 0) {
          return false
        } else {
          return true
        }
      } else {
        return true
      }
    }
  }
}
</script>

<style lang="less" scoped>
.status {
  display: flex;
  align-items: center;
  span:nth-child(1) {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 5px;
  }
  .grey {
    background-color: #ccc;
  }
  .orange {
    background-color: #faad14;
  }
  .green {
    background-color: #65c817;
  }
}
.action {
  display: flex;
  align-items: center;
  .line {
    width: 1px;
    height: 14px;
    background-color: #d8d8d8;
  }
}
.code {
  display: flex;
  flex-direction: column;
  align-items: center;
  img {
    width: 185px;
    height: 185px;
    margin-bottom: 20px;
  }
}
.btns {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
</style>
